package com.smartwebx.ha.web.admin.common;

import static com.alibaba.citrus.util.BasicConstant.EMPTY_STRING_ARRAY;
import static com.alibaba.citrus.util.ObjectUtil.defaultIfNull;
import static com.alibaba.citrus.util.StringUtil.join;
import static com.alibaba.citrus.util.StringUtil.trimToNull;

import java.io.Serializable;

import com.alibaba.citrus.util.ObjectUtil;
import com.google.common.base.Objects;

public class HaUserSys implements Serializable {
	private static final long serialVersionUID = -75075104298872596L;
	private static final ThreadLocal<HaUserSys> userHolder = new ThreadLocal<HaUserSys>();
	private Integer id;
	private String name;
	private String[] roles;
	private Integer userId;
	private Integer areaId;
	private Integer roleId;
	private String code;
	private Integer groupId;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public Integer getAreaId() {
		return areaId;
	}

	public void setAreaId(Integer areaId) {
		this.areaId = areaId;
	}

	public Integer getRoleId() {
		return roleId;
	}

	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}
	
	public Integer getGroupId() {
		return groupId;
	}

	public void setGroupId(Integer groupId) {
		this.groupId = groupId;
	}
	public static final HaUserSys getCurrentUser() {
		return userHolder.get();
	}

	public static final void setCurrentUser(HaUserSys user) {
		userHolder.set(user);
	}

	/** 创建匿名用户。 */
	public HaUserSys() {
	}

	/** 创建用户。 */
	public HaUserSys(String userId, Integer id) {
		this.name = trimToNull(userId);
		this.id = ObjectUtil.defaultIfNull(id, -1);
	}

	public String getName() {
		return name;
	}

	public Integer getId() {
		return id;
	}

	public String[] getRoles() {
		return defaultIfNull(roles, EMPTY_STRING_ARRAY);
	}

	public void setRoles(String[] roles) {
		this.roles = roles;
	}

	public void upgrade(String name, String[] roles, Integer userId,
			Integer areaId, Integer roleId,String code,Integer groupId) {
		// assertTrue(!hasLoggedIn(), ExceptionType.ILLEGAL_STATE,
		// "already logged in");

		this.name = name;
		this.userId = userId;
		this.roles = roles;
		this.roleId = roleId;
		this.areaId = areaId;
		this.code = code;
		this.groupId=groupId;
	}

	public boolean hasLoggedIn() {
		return userId != null;
	}

	public boolean isLogin() {
		return userId != null && name != null && areaId != null;
	}

	@Override
	public String toString() {
		return Objects.toStringHelper(HaUserSys.class).add("id", id)
				.add("roles", join(getRoles(), ":")).add("areaId", areaId)
				.add("roleId", roleId).add("userId", userId).add("code", code).add("groupId", groupId).toString();
	}
}
